<!--考生答题界面-->
<template>
  <div id="answer">
    <!--顶部信息栏-->
     <div class="top">
       <ul class="item">
         <li style="  list-style-type: none;"><i class="iconfont icon-menufold icon20" ref="toggle" @click="slider_flag = !slider_flag"></i></li>
         <li style="  list-style-type: none;">{{examData.examType}}-{{examData.source}}</li>
         <li style="  list-style-type: none;" @click="flag = !flag">
           <i class="iconfont icon-user icon20"></i>
           <div class="msg"  v-if="flag" @click="flag = !flag">
             <p>姓名：{{userInfo.studentName}}</p>
             <p>学号:  {{userInfo.studentId}}</p>
           </div>
         </li>
         <li><i class="iconfont icon-arrLeft icon20"></i></li>
       </ul>
     </div>
     <div class="flexarea">
        <!--左边题目编号区-->
        <transition name="slider-fade">
          <div class="left" v-if="slider_flag">
            <ul class="l-top">
              <li>
                <a href="javascript:;"></a>
                <span>当前</span>
              </li>
              <li>
                <a href="javascript:;"></a>
                <span>未答</span>
              </li>
              <li>
                <a href="javascript:;"></a>
                <span>已答</span>
              </li>
              <li>
                <a href="javascript:;"></a>
                <span>标记</span>
              </li>
            </ul>
            <div class="l-bottom">
              <div class="item">
                <p>选择题部分</p>
                <ul>
                  <li v-for="(list, index1) in topic[1]" :key="index1">
                    <a href="javascript:;"
                      @click="change(index1)"
                      :class="{'border': index == index1 && currentType == 1,'bg': bg_flag && topic[1][index1].isClick == true}">
                      <span :class="{'mark': topic[1][index1].isMark == true}"></span>
                      {{index1+1}}
                      <!--  fill(index2) 定位到该题目 -->
                      <!--  currentType 当前题目类型 -->
                      <!--  bg_flag 答题标识符，已答题改背景颜色 -->
                      <!--  topic[1][index1].isClick == true  查看是否已经被答过 -->
                      <!--  topic[1][index1].isMark == true 查看是否标识了 -->
                    </a>
                  </li>
                </ul>
              </div>

              <div class="item">
                <p>填空题部分</p>
                <ul>
                  <li v-for="(list, index2) in topic[2]" :key="index2">
                    <a href="javascript:;" @click="fill(index2)" 
                    :class="{'border': index == index2 && currentType == 2,'bg': fillAnswers[index2][3] == true}">
                      <span :class="{'mark': topic[2][index2].isMark == true}"></span>
                      {{topicCount[0]+index2+1}}
                    </a>
                  </li>
                </ul>
              </div>
              <div class="item">
                <p>判断题部分</p>
                <ul>
                  <li v-for="(list, index3) in topic[3]" :key="index3">
                    <a href="javascript:;" @click="judge(index3)"
                       :class="{'border': index == index3 && currentType == 3,
                       'bg': bg_flag && topic[3][index3].isClick == true}">
                      <span :class="{'mark': topic[3][index3].isMark == true}">
                      </span>{{topicCount[0]+topicCount[1]+index3+1}}</a>
                  </li>
                </ul>
              </div>
              <div class="final" @click="commit()">结束考试</div>
            </div>
          </div>
        </transition>

        <!--右边选择答题区-->
        <transition name="slider-fade">
        <div class="right">
          <div class="title">
            <p>{{title}}</p>
            <i class="iconfont icon-right auto-right"></i>
            <span>全卷共{{total}}题  
              <i class="iconfont icon-time"></i>
              倒计时：<b>{{time}}</b>分钟
            </span>
          </div>
          <div class="content">
            <p class="topic"><span class="number">{{number}}</span>{{currentQuestion.question}}</p>
            <div v-if="currentType == 1" >
              <el-radio-group v-model="radio[index]" @change="getChangeLabel" class="radio" >
                <el-radio calss="label" :value="1" >A. {{currentQuestion.aOption}}</el-radio>
                <el-radio :value="2" >B. {{currentQuestion.bOption}}</el-radio>
                <el-radio :value="3" >C. {{currentQuestion.cOption}}</el-radio>
                <el-radio :value="4" >D. {{currentQuestion.dOption}}</el-radio>
              </el-radio-group>
              <!-- 如果是我的练习会显示正确答案和题目解析  我的练习页面 -->
              <div class="analysis" v-if="isPractice">
                <ul>
                  <li> <el-tag type="success">正确答案：</el-tag><span class="right">{{currentQuestion.answer}}</span></li>
                  <li><el-tag>题目解析：</el-tag></li>
                  <li>{{currentQuestion.analysis == null ? '暂无解析': currentQuestion.analysis}}</li>
                </ul>
              </div>
            </div>
            <div class="fill" v-if="currentType == 2">
              <div v-for="(item,currentIndex) in blankCount" :key="currentIndex">
                <!-- 选择题和判断题使用 isClick判断是否已答题，而填空题直接使用input @blur变色，并调用fillBG表示已标记 -->
                <el-input placeholder="请填在此处"
                  v-model="fillAnswers[index][currentIndex]"
                  clearable
                  @blur="fillBG">
                </el-input>
              </div>
              <div class="analysis" v-if="isPractice">
                <ul>
                  <li> <el-tag type="success">正确姿势：</el-tag><span class="right">{{topic[2][index].answer}}</span></li>
                  <li><el-tag>题目解析：</el-tag></li>
                  <li>{{topic[2][index].analysis == null ? '暂无解析': topic[2][index].analysis}}</li>
                </ul>
              </div>
            </div>
            <div class="judge" v-if="currentType == 3">
              <el-radio-group v-model="judgeAnswer[index]" @change="getJudgeLabel" 
              v-if="currentType == 3">
                <el-radio :value="1">正确</el-radio>
                <el-radio :value="2">错误</el-radio>
              </el-radio-group>
              <div class="analysis" v-if="isPractice">
                <ul>
                  <li> <el-tag type="success">正确姿势：</el-tag><span class="right">{{topic[3][index].answer}}</span></li>
                  <li><el-tag>题目解析：</el-tag></li>
                  <li>{{topic[3][index].analysis == null ? '暂无解析': topic[3][index].analysis}}</li>
                </ul>
              </div>
            </div>
          </div>
          <div class="operation">
            <ul class="end">
              <li @click="previous()"><i class="iconfont icon-previous"></i><span>上一题</span></li>
              <li @click="mark()"><i class="iconfont icon-mark-o"></i><span>标记</span></li>
              <li @click="next()"><span>下一题</span><i class="iconfont icon-next"></i></li>
            </ul>
          </div>
        </div>
        </transition>
     </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import useUserStore from '@/store/modules/user'
import {getExam, getPaperQuestionList} from '@/api/module/exam'
import {getStudentByUserId} from '@/api/module/student'
import {submitPaper} from '@/api/student/score/score'

// 路由和状态管理
const route = useRoute();
const router = useRouter();
const userStore = useUserStore()

// 响应式数据
const slider_flag = ref(true);
const flag = ref(false);
const showSubmitDialog = ref(false);
const time = ref(0);
const timer = ref(null);
const bg_flag = ref(false); // 添加 bg_flag
const radio = ref([]); // 添加选择题答案数组
const judgeAnswer = ref([]); // 添加判断题答案数组
const fillAnswers = ref([[]]);
const index = ref(0); // 当前题目索引 (替代 currentIndex)
const total=ref(0);//题目总数
const startTime = ref(null);//考试开始时间
const endTime = ref(null);//考试结束时间

// 学生信息
const userInfo = ref({
  studentName: 'hhhh',
  studentId: 1111111,
});


// 考试数据
const examData = ref({
  source: '',
  totalTime: 0,
  examtype: '',
  examCode: '',
  paperId: 0,
  paperDetail: [],
});

// 题目数据
const topic = reactive({
  1: [],
  2: [],
  3: []
});

const topicCount = ref([0, 0, 0]); // 初始化为 [0,0,0]

//当前题目的试题类型
const currentType = ref(1); // 1:选择题, 2:填空题, 3:判断题

// 计算属性
const isPractice = ref(true)

// 题目类型标题
const title = computed(() => {
  switch (currentType.value) {
    case 1: return "请选择正确的选项";
    case 2: return "请在横线处填写答案";
    case 3: return "请作出正确判断";
    default: return "";
  }
});

// 当前题目信息
const currentQuestion = computed(() => {
  return topic[currentType.value][index.value] || {};
});

// 题目编号
const number = computed(() => {
  switch (currentType.value) {
    case 1: return index.value + 1;
    case 2: return topicCount.value[0] + index.value + 1;
    case 3: return topicCount.value[0] + topicCount.value[1] + index.value + 1;
    default: return 1;
  }
});

// 填空题空格数量
const blankCount = computed(() => {
  if (currentType.value !== 2) return 0;
  return (currentQuestion.value.question?.split("()").length - 1) || 0;
});

// 生命周期钩子
onMounted(() => {
  getExamData();
  startTimer();
});

onBeforeUnmount(() => {
  clearInterval(timer.value);
});

// 方法
const getExamData = async () => {
  try {
    //获取考试信息和用户信息
    const studentRes=await getStudentByUserId(userStore.id)
    userInfo.value.studentId=studentRes.data.studentId
    userInfo.value.studentName=studentRes.data.studentName
    
    const examCode = route.query.examCode;
    const examRes =  await getExam(examCode)
    // 记录考试开始时间
    startTime.value = new Date();
    
    Object.assign(examData.value, examRes.data);
    time.value = examData.value.totalTime;
    
    // 获取试卷题目
    const paperRes = await getPaperQuestionList({examCode:examCode})
    
    // 处理题目数据// 1:选择题, 2:填空题, 3:判断题
    topic[1] = paperRes.rows.filter(q => q.questionType === '2');
    topic[2] = paperRes.rows.filter(q => q.questionType === '3');
    topic[3] = paperRes.rows.filter(q => q.questionType === '1');

    //设置题目数量
    total.value=paperRes.total
    
    // 设置题目数量
    topicCount.value = [
      topic[1].length,
      topic[2].length,
      topic[3].length
    ];
    
    // 初始化填空题答案数组
    fillAnswers.value = Array(topicCount.value[1]).fill().map(() => [null, null, null, false]);
    
  } catch (error) {
    ElMessage.error('获取考试数据失败');
    console.error(error);
  }
};

//计时器
const startTimer = () => {
  timer.value = setInterval(() => {
    if (time.value > 0) {
      time.value--;
      
      // 倒计时提醒
      if (time.value === 10) {
        ElMessage.warning('考生注意，考试时间还剩10分钟！');
      }
      
      // 考试结束自动提交
      if (time.value === 0) {
        clearInterval(timer.value);
        submitExam();
      }
    }
  }, 60000); // 每分钟更新一次
};

// 导航方法
const change = (idx) => {
  currentType.value = 1;
  index.value = idx;
};

const fill = (idx) => {
  currentType.value = 2;
  index.value = idx;
};

const judge = (idx) => {
  currentType.value = 3;
  index.value = idx;
};

const previous = () => {
  if (index.value > 0) {
    index.value--;
  } else {
    // 跨题型导航
    if (currentType.value === 2 && topicCount.value[0] > 0) {
      currentType.value = 1;
      index.value = topicCount.value[0] - 1;
    } else if (currentType.value === 3 && topicCount.value[1] > 0) {
      currentType.value = 2;
      index.value = topicCount.value[1] - 1;
    }
  }
};

const next = () => {
  const currentCount = topicCount.value[currentType.value - 1];
  
  if (index.value < currentCount - 1) {
    index.value++;
  } else {
    // 跨题型导航
    if (currentType.value === 1 && topicCount.value[1] > 0) {
      currentType.value = 2;
      index.value = 0;
    } else if (currentType.value === 2 && topicCount.value[2] > 0) {
      currentType.value = 3;
      index.value = 0;
    } else if (currentType.value === 3 && topicCount.value[0] > 0) {
      currentType.value = 1;
      index.value = 0;
    }
  }
};

const mark = () => {
  topic[currentType.value][index.value].isMark = true;
  ElMessage.success('题目已标记');
};

const getChangeLabel = (val) => {
  bg_flag.value = true;
  topic[1][index.value].isClick = true;
};

const getJudgeLabel = (val) => {
  bg_flag.value = true;
  topic[3][index.value].isClick = true;
};

const fillBG = () => {
  if (fillAnswers.value[index.value][0] !== null) {
    fillAnswers.value[index.value][3] = true;
  }
};


//提交考试, //答案提交计算分数
const commit = async () => {
  /* 计算选择题总分 */
  let finalScore = 0;
  
  // 1. 计算选择题分数
  radio.value.forEach((element, idx) => {
    if (element != null) {
      let selectedAnswer = "";
      switch (element) {
        case 1: selectedAnswer = "A"; break;
        case 2: selectedAnswer = "B"; break;
        case 3: selectedAnswer = "C"; break;
        case 4: selectedAnswer = "D"; break;
      }
      
      if (topic[1][idx] && selectedAnswer === topic[1][idx].answer) {
        finalScore += topic[1][idx].score;
      }
    }
  });
  
  // 2. 计算填空题分数
 fillAnswers.value.forEach((answers, idx) => {
    if (topic[2][idx]) {
      const correctAnswer = topic[2][idx].answer;
      let allCorrect = true;
      
      // 使用中文逗号分割正确答案
      const correctParts = correctAnswer.split("，"); // 注意这里是中文逗号
      
      // 检查每个填空是否都正确
      for (let i = 0; i < correctParts.length; i++) {
        // 如果用户答案未定义或与正确答案不匹配
        if (i >= answers.length || answers[i] !== correctParts[i]) {
          allCorrect = false;
          break;
        }
      }
      
      if (allCorrect) {
        finalScore += topic[2][idx].score;
      }
    }
  })
  
  // 3. 计算判断题分数
  judgeAnswer.value.forEach((answer, idx) => {
    if (topic[3][idx]) {
      const selectedAnswer = answer === 1 ? "T" : "F";
      if (selectedAnswer === topic[3][idx].answer) {
        finalScore += topic[3][idx].score;
      }
    }
  });
  

  // 记录结束时间
  endTime.value = new Date();
  
  // 时间判断
  if (time.value !== 0) {
    try {
      const confirmResult = await ElMessageBox.confirm(
        "考试结束时间未到,是否提前交卷?",
        "友情提示",
        {
          confirmButtonText: "立即交卷",
          cancelButtonText: "再检查一下",
          type: "warning",
        }
      );
      
      if (confirmResult === "confirm") {
        submitAndJump(finalScore)
      }
    } catch (cancel) {
      console.log("继续答题");
    }
  } else {
    // 时间已到，自动提交
    ElMessage.success("考试时间结束，已自动提交试卷!");
    //提交并跳转路由
    submitAndJump(finalScore)
  }
}


//提交并跳转路由
const submitAndJump=(finalScore)=>{

          console.log('跳转')
          //提交并跳转路由
        const now = new Date();
      const answerDate = formatDate(now);
      const start = formatDate(startTime.value);
      const end = formatDate(endTime.value);
      //提交试卷
          submitPaper({
          examCode:examData.value.examCode,
          examName: examData.value.source+examData.value.description,
          userId: userStore.id,
          subject: examData.value.source,
          etScore: finalScore,
          answerDate: answerDate,
        })
      //跳转
      router.push({
      path: "/answerEnd",
      query: {
        score: finalScore,
        startTime: start,  // 添加开始时间
        endTime: end,      // 添加结束时间
        studentName:userInfo.value.studentName,//学生名字
        examName: examData.value.source+examData.value.description,
        totalTime:examData.value.totalTime,
        totalScore:examData.value.totalScore,
      }
    })
    
}

// 日期格式化函数
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const submitExam = async () => {
  try {
    // 这里应该有实际的提交逻辑
    ElMessage.success('考试提交成功');
    router.push('/studentScore');
  } catch (error) {
    ElMessage.error('提交试卷失败');
    console.error(error);
  }
};
</script>

<style lang="less">
.iconfont.icon-time {
  color: #2776df;
  margin: 0px 6px 0px 20px;
}
.analysis {
  margin-top: 20px;
  .right {
    color: #2776df;
    font-size: 18px;
    border: 1px solid #2776df;
    padding: 0px 6px;
    border-radius: 4px;
    margin-left: 20px;
  }
  ul li:nth-child(2) {
    margin: 20px 0px;
  }
  ul li:nth-child(3) {
    padding: 10px;
    background-color: #d3c6c9;
    border-radius: 4px;
  }
}
.analysis span:nth-child(1) {
  font-size: 18px;
}
.mark {
  position: absolute;
  width: 4px;
  height: 4px;
  content: "";
  background-color: red;
  border-radius: 50%;
  top: 0px;
  left: 22px;
}
.border {
  position: relative;
  border: 1px solid #FF90AA !important;
}
.bg {
  background-color: #5188b8 !important;
}
.fill .el-input {
  display: inline-flex;
  width: 150px;
  margin-left: 20px;
  .el-input__inner {
    border: 1px solid transparent;
    border-bottom: 1px solid #eee;
    padding-left: 20px;
  }
}
/* slider过渡效果 */
.slider-fade-enter-active {
  transition: all .3s ease;
}
.slider-fade-leave-active {
  transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slider-fade-enter, .slider-fade-leave-to {
  transform: translateX(-100px);
  opacity: 0;
}

.operation .end li:nth-child(2) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgb(39, 118, 223);
  border-radius: 50%;
  width: 50px;
  height: 50px;
  color: #fff;
}
.operation .end li {
  cursor: pointer;
  margin: 0 100px;
}
.operation {
  background-color: #fff;
  border-radius: 4px;
  padding: 10px 0px;
  margin-right: 10px;
}
.operation .end {
  display: flex;
  justify-content: center;
  align-items: center;
  color: rgb(39, 118, 223);
}
.content .number {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 20px;
  height: 20px;
  background-color: rgb(39, 118, 223);
  border-radius: 4px;
  margin-right: 4px;
}
.content {
  padding: 0px 20px;
}
.content .topic {
  padding: 20px 0px;
  padding-top: 30px;
}
.right .content {
  background-color: #fff;
  margin: 10px;
  margin-left: 0px;
  height: 470px;
}
.content .el-radio-group label {
  color: #000;
  margin: 5px 0px;
  text-align: left;  /* 确保文本对齐到左侧 */
}
.content .el-radio-group {
  display: flex;
  flex-direction:column;
  align-items: flex-start;  /* 确保所有单选框都靠左 */
}
.right .title p {
  margin-left: 20px;
}
.flexarea {
  display: flex;
}
.flexarea .right {
  flex: 1;
}
.auto-right {
  margin-left: auto;
  color: #2776df;
  margin-right: 10px;
}
.right .title {
  margin-right: 10px;
  padding-right: 30px;
  display: flex;
  margin-top: 10px;
  background-color: #fff;
  height: 50px;
  line-height: 50px;
}
.clearfix {
  clear: both;
}
.l-bottom .final {
  cursor: pointer;
  display: inline-block;
  text-align: center;
 background-color: rgb(39, 118, 223);
  width: 240px;
  margin: 20px 0px 20px 10px;
  border-radius: 4px;
  height: 30px;
  line-height: 30px;
  color: #fff;
  margin-top: 22px;
}
#answer .left .item {
  padding: 0px;
  font-size: 16px;
}
.l-bottom {
  border-radius: 4px;
  background-color: #fff;
}
.l-bottom .item p {
  margin-bottom: 15px;
  margin-top: 10px;
  color: #000;
  margin-left: 10px;
  letter-spacing: 2px;
}
.l-bottom .item li {
  width: 15%;
  margin-left: 5px;
  margin-bottom: 10px;
}
.l-bottom .item {
  display: flex;
  flex-direction: column;
}
.l-bottom .item ul {
  width: 100%;
  margin-bottom: -8px;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}
.l-bottom .item ul li a {
  position: relative;
  justify-content: center;
  display: inline-flex;
  align-items: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #fff;
  border: 1px solid #eee;
  text-align: center;
  color: #000;
  font-size: 16px;
}
.left .l-top {
  display: flex;
  justify-content: space-around;
  padding: 16px 0px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
  background-color: #fff;
}
.left {
  width: 260px;
  height: 100%;
  margin: 10px 10px 0px 10px;
}
.left .l-top li:nth-child(2) a {
  border: 1px solid #eee;
}
.left .l-top li:nth-child(3) a {
  background-color: #5188b8;
  border: none;
}
.left .l-top li:nth-child(4) a {
  position: relative;
  border: 1px solid #eee;
}
.left .l-top li:nth-child(4) a::before {
  width: 4px;
  height: 4px;
  content: " ";
  position: absolute;
  background-color: red;
  border-radius: 50%;
  top: 0px;
  left: 16px;
}
.left .l-top li {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.left .l-top li a {
  display: inline-block;
  padding: 10px;
  border-radius: 50%;
  background-color: #fff;
  border: 1px solid #FF90AA;
}
#answer .top {
  background-color: rgb(39, 118, 223);
}
#answer .item {
  color: #fff;
  display: flex;
  padding: 20px;
  font-size: 20px;
}
#answer .top .item li:nth-child(1) {
  margin-right: 10px;
}
#answer .top .item li:nth-child(3) {
  position: relative;
  margin-left: auto;
}
#answer {
  padding-bottom: 30px;
}
.icon20 {
  font-size: 20px;
  font-weight: bold;
}
.item .msg {
  padding: 10px 15px;
  border-radius: 4px;
  top: 47px;
  right: -30px;
  color: #6c757d;
  position: absolute;
  border: 1px solid rgba(0,0,0,.15);
  background-color: #fff;
}
.item .msg p {
  font-size: 16px;
  width: 200px;
  text-align: left;
}
</style>
